﻿using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.html;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using WeSpot.Models;

namespace WeSpot.Controllers
{

   
    public class SecureController : Controller
    {
        //
        // GET: /Secure/
        //[Authorize(Users = "shailendra,mohan")]
        //[Authorize(Roles = "Admin,SubAdmin")]
        [Authorize]
        public ActionResult Index()
        {

            

            //HttpContext.Session["UserName"];
            //HttpContext.Session["ProviderUserId"];
            //HttpContext.Session["Provider"];
            var oauthID = HttpContext.Session["oauthID"];
            var oauthProvider = HttpContext.Session["oauthProvider"];
            if (oauthID == null || oauthProvider == null)
            {
                return RedirectToAction("Login", "Account");
            }
            var oauthIDSimple = extractUser(oauthID.ToString(), oauthProvider.ToString());
            var oauthProviderSimple = convertProvider(oauthProvider.ToString());

			//string uri = @"http://inquiry.wespot.net/services/api/rest/xml/?method=user.inquiries&api_key=27936b77bcb9bb67df2965c6518f37a77a7ab9f8&oauthId=105514866316046533487&oauthProvider=Google";
			//string uri = @"http://inquiry.wespot.net/services/api/rest/xml/?method=user.inquiries&api_key=27936b77bcb9bb67df2965c6518f37a77a7ab9f8&oauthId=stefaan.ternier&oauthProvider=weSPOT";
            string uri = @"http://inquiry.wespot.net/services/api/rest/xml/?method=user.inquiriesAdmin&api_key=27936b77bcb9bb67df2965c6518f37a77a7ab9f8&oauthId=" + oauthIDSimple + "&oauthProvider=" + oauthProviderSimple;
            if (HttpContext.Session["Lang"] == null)
            {
                HttpContext.Session.Add("Lang", 2);
            }
            
            
            
            /*WebRequest request = WebRequest.Create(uri);
            
            WebResponse response = request.GetResponse();

            WeSpot.Models.elgg elggList;

            using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
            {

                XmlSerializer serializer = new XmlSerializer(typeof(WeSpot.Models.elgg));

                elggList = (WeSpot.Models.elgg)serializer.Deserialize(sr);
                sr.Close();
            }*/

            /*
            Session.Add("UserName", result.UserName);
            Session.Add("ProviderUserId", result.ProviderUserId);
            Session.Add("Provider", result.Provider);
            Session.Add("oauthID", result.ProviderUserId);
            Session.Add("oauthProvider", result.Provider);
            */

            //return View(elggList);

//            return View(ElggUtils.RestRequest(uri));
            return View(ElggUtils.GetUserInquiries(oauthIDSimple, oauthProviderSimple));

        }

        private string extractUser(string userComplete, string provider)
        {
            if (provider.Equals("google"))
                return HttpContext.Session["oauthID"].ToString().Substring(HttpContext.Session["oauthID"].ToString().IndexOf("=") + 1, HttpContext.Session["oauthID"].ToString().Length - 1 - HttpContext.Session["oauthID"].ToString().IndexOf("="));
            if (provider.Equals("facebook"))
                return userComplete;
            if (provider.Equals("wespot"))
                return userComplete;
            return "";
        }
        private string convertProvider(string provider)
        {
            if (provider.Equals("google"))
                return "Google";
            if (provider.Equals("facebook"))
                return "Facebook";
            if (provider.Equals("wespot"))
                return "weSPOT";
            return "";
        }
        //
        // GET: /Secure/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        public string GetUserMail(string oauthId, string oauthProvider )
        {
            WeSpot.Models.ElggString.elgg elggList = ElggUtils.GetUserMail(oauthId, oauthProvider);
            //return ElggUtils.Serialize<WeSpot.Models.ElggString.elgg>(elggList);
            return elggList.result.Value;
        }
        /// <summary>
        /// GetInquiryId
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetInquiryId(int id)
        {
            if (Session["OauthIdTOUserName"]==null)
                RedirectToAction("Login", "Account");
            WeSpot.Models.elgg elggList = ElggUtils.GetInquiryUsers(id + "");

            //Alimento la Hashtable per il mapping OauthId - UserName da usare in Data (ad esempio)

            ((Hashtable)(Session["OauthIdTOUserName"])).Clear();
            ((Hashtable)(Session["OauthIdTOProvider"])).Clear();
            ((Hashtable)(Session["OauthPlusProviderIdTOIcon"])).Clear();
            for (int i = 0; i < elggList.result.array_item.Length; i++)
            {
                ((Hashtable)(Session["OauthIdTOUserName"])).Add(elggList.result.array_item[i].oauthId.Value, elggList.result.array_item[i].name.Value);
                ((Hashtable)(Session["OauthIdTOProvider"])).Add(elggList.result.array_item[i].oauthId.Value, elggList.result.array_item[i].oauthProvider.Value);
                ((Hashtable)(Session["OauthPlusProviderIdTOIcon"])).Add(elggList.result.array_item[i].oauthId.Value + "_" + elggList.result.array_item[i].oauthProvider.Value, elggList.result.array_item[i].icon.Value);
            }
            //TO DO : aggiunta mail ... come recupero mail ???
            return ElggUtils.Serialize<WeSpot.Models.elgg>(elggList);
        }

        /// <summary>
        /// Get the response for an inquiry, for a specific user
        /// </summary>
        /// <param name="inquiryId"></param>
        /// <returns></returns>
        public string GetUserRunResponses(string inquiryId, string provider, string oauthId)
        {
            ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId);

            return ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", new DateTime(1970, 1, 1), provider, oauthId)).OuterXml;
        }

        //
        // GET: /Secure/Create

        //Da cambiare con IdUtente ecc ecc
        public string GetUserMap(int inquiryId)
        {
            StringBuilder data = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-16\"?><elgg xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">");

            //Recupero tutti gli utenti e prendo l'ultimo evento per avere la posizione
            WeSpot.Models.elgg elggList = ElggUtils.GetInquiryUsers(inquiryId + "");

            ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId + "");


            var xml = ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", new DateTime(1970, 1, 1), Session["oauthProvider"].ToString(), Session["oauthID"].ToString())).OuterXml;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList elemListLat = doc.GetElementsByTagName("lat");
            XmlNodeList elemListLng = doc.GetElementsByTagName("lng");
            XmlNodeList elemListUserEmail = doc.GetElementsByTagName("userEmail");

            for(int i=0; i<elggList.result.array_item.Length; i++)
                {
                var oauthId = elggList.result.array_item[i].oauthId.Value;
                var oauthProvider = elggList.result.array_item[i].oauthProvider.Value;


                for (int ii = elemListUserEmail.Count - 1; ii >= 0; ii--)
                {
                    if (elemListUserEmail[ii].OuterXml.Contains(oauthId) && (!(elemListLat[ii].InnerXml.Equals("0")) || !(elemListLng[ii].InnerXml.Equals("0"))))
                    {
                            data.Append("<users>"
                         + "<IdUtente>" + elggList.result.array_item[i].oauthId.Value + "</IdUtente>"
                         + "<providerIdUtente>" + elggList.result.array_item[i].oauthProvider.Value + "</providerIdUtente>"
                         + "<userName>" + elggList.result.array_item[i].name.Value + "</userName>"
                         + "<imageUser type=\"string\">" + elggList.result.array_item[i].icon.Value + "</imageUser>"
                         + "<userLat type=\"string\">" + elemListLat[ii].InnerXml + "</userLat>"
                         + "<userLon type=\"string\"> " + elemListLng[ii].InnerXml + "</userLon>"
                         + "</users>");
                            ii = -1;
                   }
                }  
                
                //var itemtypeValue = doc.Root.Element("").Value;
            
            }
            data.Append("</array_item></result></elgg>");
            return data.ToString();
            //return ElggUtils.Serialize<WeSpot.Models.elgg>(elggList);
            /*
            String test = "<?xml version=\"1.0\" encoding=\"utf-16\"?><elgg xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">"
                  + "<users>"
                  + "<IdUtente>A</IdUtente>"
                  + "<imageUser type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1395242006&joindate=1395242004&guid=31560&size=medium</imageUser>"
                  + "<userLat type=\"string\">44.405658</userLat>"
                  + "<userLon type=\"string\">8.952934</userLon>"
                  + "</users>"
                  + "<users>"
                  + "<IdUtente>B</IdUtente>"
                  + "<imageUser type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1394697616&joindate=1394697606&guid=31125&size=medium</imageUser>"
                  + "<userLat type=\"string\"> 45.066866</userLat>"
                  + "<userLon type=\"string\">7.686740</userLon>"
                  + "</users>"
                  + "<users>"
                  + "<IdUtente>C</IdUtente>"
                  + "<imageUser type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium</imageUser>"
                  + "<userLat type=\"string\">45.458819</userLat>"
                  + "<userLon type=\"string\">9.173395</userLon>"
                  + "</users>"
                  + "</array_item></result></elgg>";
            return test;*/
        }

        //Da cambiare con IdUtente ecc ecc
        public string GetUserHistoryMap(string inquiryId,string idUtente, string providerIdUtente, string dataFrom)
        {
            String test = "<?xml version=\"1.0\" encoding=\"utf-16\"?><elgg xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">"
                  + "<user>"
                  + "<IdUtente>A</IdUtente>"
                  + "<actions>"
                  + "<action>"
                  + "<actionType type=\"string\">A</actionType>"
                  + "<actionDescription type=\"string\">desrizione dell azione</actionDescription>"
                  + "<actionDate type=\"string\">24/02/2014</actionDate>"
                  + "<actionImage type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium</actionImage>"
                  + "<actionLat type=\"string\">45.026866</actionLat>"
                  + "<actionLon type=\"string\">7.626740</actionrLon>"
                  + "</action>"
                  + "<actions/>"
                  + "</user>"
                
                  + "</array_item></result></elgg>";
            StringBuilder data = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-16\"?><elgg xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">");
            data.Append("<user><actions>");
            //Recupero tutti gli utenti e prendo l'ultimo evento per avere la posizione
            WeSpot.Models.elgg elggList = ElggUtils.GetInquiryUsers(inquiryId + "");

            ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId + "");


            //var xml = ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", new DateTime(1970, 1, 1), Session["oauthProvider"].ToString(), Session["oauthID"].ToString())).OuterXml;
            var xml = ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", new DateTime(1970, 1, 1), providerIdUtente,idUtente)).OuterXml;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList elemListLat = doc.GetElementsByTagName("lat");
            XmlNodeList elemListLng = doc.GetElementsByTagName("lng");
            XmlNodeList elemListUserEmail = doc.GetElementsByTagName("userEmail");

            //for (int i = 0; i < elggList.result.array_item.Length; i++)
            //{
            //    var oauthId = elggList.result.array_item[i].oauthId.Value;
            //    var oauthProvider = elggList.result.array_item[i].oauthProvider.Value;


                for (int ii = 0; ii< elemListUserEmail.Count; ii++)
                {
                    string providerCode = elemListUserEmail[ii].InnerXml.Split(':')[0];
                    string userId = elemListUserEmail[ii].InnerXml.Split(':')[1];
                    string proveideId = ARLearnUtils.GetProviderDescription(Int16.Parse(providerCode));


                    if (elemListUserEmail[ii].OuterXml.Contains(idUtente) && providerIdUtente.ToLower().Equals(proveideId.ToLower()) && (!(elemListLat[ii].InnerXml.Equals("0")) || !(elemListLng[ii].InnerXml.Equals("0"))))
                    {
                        string actionImage = "";
                        string actionType = "";
                        if (JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["imageUrl"] != null)
                        {
                            actionType = "imageUrl";
                            actionImage = JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["imageUrl"].ToString();
                        }
                        if (JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["videoUrl"] != null)
                        {
                            actionType = "videoUrl";
                            actionImage = JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["videoUrl"].ToString();
                        }
                        if (JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["text"] != null)
                        {
                            actionType = "text";
                            actionImage = JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["text"].ToString();
                        }
                        if (JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["audioUrl"] != null)
                        {
                            actionType = "audioUrl";
                            actionImage = JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["audioUrl"].ToString();
                        }
                        if (JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["value"] != null)
                        {
                            actionType = "value";
                            actionImage = JObject.Parse(doc.GetElementsByTagName("responseValue")[ii].InnerXml)["value"].ToString();
                        }

                        data.Append("<action>");
                        data.Append("<actionType type=\"string\">" + actionType + "</actionType>");
                        data.Append("<actionDescription type=\"string\">" + new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(Double.Parse(doc.GetElementsByTagName("timestamp")[0].InnerXml) / 1000d)).ToLocalTime().ToString() + "</actionDescription>");//
                        data.Append("<actionDate type=\"string\">" + "--" + "</actionDate>");
                        data.Append("<actionImage type=\"string\"> " + actionImage + "</actionImage>");
                        data.Append("<actionLat type=\"string\"> " + elemListLat[ii].InnerXml + "</actionLat>");
                        data.Append("<actionLon type=\"string\">" + elemListLng[ii].InnerXml + "</actionLon>");
                        data.Append("</action>");
                    }
                }
                //var itemtypeValue = doc.Root.Element("").Value;
            //}
            data.Append("</actions></user>");
            data.Append("</array_item></result></elgg>");
            return data.ToString();
        }


        public string GetUserData(int inquiryId)
        {
            StringBuilder data = new StringBuilder("<data xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<status type=\"integer\">0</status>" +
                "<result type=\"array\">" +
                "<array_item type=\"array\">" +
                "<argomenti>" +
                    "<argomento><label>Pictures</label><value>Pictures</value></argomento>" +
                    "<argomento><label>Video</label><value>Video</value></argomento>" +
                    "<argomento><label>Audio</label><value>Audio</value></argomento>" +
                    "<argomento><label>Text</label><value>Text</value></argomento>" +
                    "<argomento><label>Numeric</label><value>Numeric</value></argomento>" +
                "</argomenti>" +
                "<users>");

            //Recupero tutti gli utenti e prendo l'ultimo evento per avere la posizione
            WeSpot.Models.elgg elggList = ElggUtils.GetInquiryUsers(inquiryId + "");


            ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId + "");


            var xml = ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", new DateTime(1970, 1, 1), Session["oauthProvider"].ToString(), Session["oauthID"].ToString())).OuterXml;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList elemListUserEmail = doc.GetElementsByTagName("userEmail");
            XmlNodeList elemListrResponseValue = doc.GetElementsByTagName("responseValue");

            for (int i = 0; i < elggList.result.array_item.Length; i++)
            {
                var oauthId = elggList.result.array_item[i].oauthId.Value;
                var oauthProvider = elggList.result.array_item[i].oauthProvider.Value;

                //elggList.result.array_item[i].inquiryId è null usa quello della chiamata
                
                //XDocument doc = XDocument.Parse(xml);
                
                int numImage = 0;
                int numtext =  0;
                int numaudio = 0;
                int numvideo = 0;
                int numNumeric = 0;
                for (int ii = 0; ii < elemListUserEmail.Count; ii++)
                {
                    if (elemListUserEmail[ii].InnerXml.Contains(oauthId))
                    {

                        numImage += Regex.Matches(elemListrResponseValue[ii].InnerXml, "imageUrl").Count;
                        numtext += Regex.Matches(elemListrResponseValue[ii].InnerXml, "text").Count;
                        numaudio += Regex.Matches(elemListrResponseValue[ii].InnerXml, "audioUrl").Count;
                        numvideo += Regex.Matches(elemListrResponseValue[ii].InnerXml, "videoUrl").Count;
                        numNumeric += Regex.Matches(elemListrResponseValue[ii].InnerXml, "value").Count;

                    }
                    //Console.WriteLine(elemList[ii].InnerXml);
                }
                data.Append("<user>" +
                    "<IdUtente>" +oauthId + "</IdUtente>" +
                    "<UserName>" + ((Hashtable)(Session["OauthIdTOUserName"]))[oauthId] + "</UserName>" +
                    "<listaArgomenti>" +
                    "<argomento>" + numImage + "</argomento>" +
                    "<argomento>" + numvideo + "</argomento>" +
                    "<argomento>" + numaudio + "</argomento>" +
                    "<argomento>" + numtext + "</argomento>" +
                    "<argomento>" + numNumeric + "</argomento>" +
                    "</listaArgomenti>" +

                    "<imageUser type=\"string\">" + ((Hashtable)(Session["OauthPlusProviderIdTOIcon"]))[oauthId + "_" + oauthProvider] + "</imageUser>" +
                    "<userLat type=\"string\">44.405658</userLat>" +
                    "<userLon type=\"string\">8.952934</userLon>" +
                    "</user>");
            }
                return data.ToString();
        }


        [HttpGet]
        public String GiveBadges(string user, string badgeLabel, string badgeValue)
        {
            return "dato il badge a user : " + user + " - badgeLabel : " + badgeLabel + " - badgeValue : " + badgeValue;
        }

        public String GetUsersBadges(int inquiryId)
        {
            StringBuilder UsersBadges = new StringBuilder(
             "<medaglie xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
            "<status type=\"integer\">0</status>" +
            "<result type=\"array\">" +
            "<array_item type=\"array\">" +
            "<argomenti>");

            /*
             models
             BadgeUtils
             //Colonne
             List<BadgeId> =GetBadgesByContent(InquryId)

             for(List<BadgeId>)
                (string)badge = GetBadgeByIdentifies(BadgeId)
 
                (obj)badge=JsonToBadgeJsonObject(badge)
 
             //Assegnetari

             Lista(UserId) = GetAwardById(idBadge)
             */

            //COLONNE
            Hashtable BadgeToUsersAwarded = new Hashtable();
            Hashtable UsersAwardedwihtBadges = new Hashtable();
            String BadgesId = BadgeUtils.GetBadgeByContext(inquiryId + "");
            JArray o1 = JArray.Parse(BadgesId);
            for (int i = 0; i < o1.Count; i++)
            {
                string badgeId = o1[i]["id"].ToString();
                string badgeLabel = o1[i]["jsonBadge"]["description"].ToString();
                string badgeImage = o1[i]["jsonBadge"]["image"].ToString();

                UsersBadges.Append("<argomento><id>" + badgeId + "</id><label>" + badgeLabel + "</label><value>" + badgeImage + "</value></argomento>");
                BadgeToUsersAwarded.Add(badgeId, BadgeUtils.GetAwardByBadgeId(badgeId));
            }
             UsersBadges.Append("</argomenti>");



             Hashtable AwardPerUserId = new Hashtable();
             Hashtable ProviderPerUserId = new Hashtable();

            //Per ogni Badge la lista degli utenti che hanno avuto l'award (contenente il riferimento al badge)
            foreach(var usersPerBadge1 in BadgeToUsersAwarded)
            //for(int j =0; j<BadgeToUsersAwarded.Keys.Count j++)
            {
                
                if( !( ((DictionaryEntry)usersPerBadge1).Value.Equals("[]") ) )
                {
                    JArray usersPerBadge = JArray.Parse(((DictionaryEntry)usersPerBadge1).Value.ToString());

                    for(int k=0; k<usersPerBadge.Count; k++)
                    {
                        String awardId = usersPerBadge[k]["id"].ToString();
                        String userId =  usersPerBadge[k]["username"].ToString().Split('_')[1];
                        String providerUserId = usersPerBadge[k]["username"].ToString().Split('_')[0];

                        if (!AwardPerUserId.ContainsKey(userId))
                        {
                            //una volta sola tanto la lista è sempre la stessa ...
                            string listAwarId = BadgeUtils.GetAwardByUser(providerUserId, userId);
                            AwardPerUserId.Add(userId,listAwarId);
                            ProviderPerUserId.Add(userId, providerUserId);
                        }
                    }
                    /*
                     * 
                        BadgeToUsersAwarded.Add(badgeId, BadgeUtils.GetAwardByBadgeId(badgeId));
                        AwardPerUserId.Add(userId,listAwarId);
                        ProviderPerUserId.Add(userId, providerUserId); 
                     
                    if (!(UsersAwardedwihtBadges.ContainsKey(userId)))
                    {
                        List<String> listabadgesperutente = new List<String>();
                        listabadgesperutente.Add(badgeId);
                        UsersAwardedwihtBadges.Add(userId, listabadgesperutente);
                    }
                    else
                        ((List<String>)(UsersAwardedwihtBadges[userId])).Add(badgeId);
                    */
                    //interseca listAwarId con usersPerBadge1
                }
                //JArray usersPerBadge = JArray.Parse(usersPerBadge1.ToString());
                   //BadgeToUsersAwarded[BadgeToUsersAwarded.Keys[j]].ToString());
                
            }
            //Incorocio
            //Creo tutte le liste vuote
            foreach(var uid in ((Hashtable)(Session["OauthIdTOUserName"])).Keys)
            {
                List<String> listabadgesperutente = new List<String>();
                UsersAwardedwihtBadges.Add(uid, listabadgesperutente);
            }

            foreach(var userId in AwardPerUserId.Keys)
            {
                JArray ListaAwardPerUser = JArray.Parse((String)(AwardPerUserId[userId]));
                string providerPerUser = (String)(ProviderPerUserId[userId]);
                foreach (var badgeId in BadgeToUsersAwarded.Keys)
                {
                    JArray listaAwardPerBadge = JArray.Parse((String)(BadgeToUsersAwarded[badgeId]));

                    for (int kk = 0; kk < ListaAwardPerUser.Count; kk++)
                        for (int jj = 0; jj < listaAwardPerBadge.Count; jj++)
                            if (ListaAwardPerUser[kk]["id"].Equals(listaAwardPerBadge[jj]["id"]))




                                   

                                    if(!((List<String>)(UsersAwardedwihtBadges[userId])).Contains((string)badgeId))
                                        ((List<String>)(UsersAwardedwihtBadges[userId])).Add((string)badgeId);
                }
            }

    //BadgeToUsersAwarded.Add(badgeId, BadgeUtils.GetAwardByBadgeId(badgeId));
    //AwardPerUserId.Add(userId,listAwarId);
    //ProviderPerUserId.Add(userId, providerUserId); 



    UsersBadges.Append("<users>");

    foreach (var user in UsersAwardedwihtBadges.Keys)
    {
    UsersBadges.Append("<user>");
    UsersBadges.Append("<IdUtente>" + user + "</IdUtente>");
    UsersBadges.Append("<listaMedaglie>");
    List<String> listaperutente = ((List<String>)(UsersAwardedwihtBadges[user]));
    for (int x = 0; x < listaperutente.Count; x++)
    {
        UsersBadges.Append("<Medaglia>" + listaperutente[x] + "</Medaglia>"); 
    }
    UsersBadges.Append("</listaMedaglie>");
    UsersBadges.Append("<imageUser type=\"string\">" + ((Hashtable)(Session["OauthPlusProviderIdTOIcon"]))[user + "_" + ((Hashtable)(Session["OauthIdTOProvider"]))[user]] + "</imageUser>");
    UsersBadges.Append("<username>" + ((Hashtable)(Session["OauthIdTOUserName"]))[user] + "</username>");
    UsersBadges.Append("<userLat type=\"string\">44.405658</userLat>");
    UsersBadges.Append("<userLon type=\"string\">8.952934</userLon>");
    UsersBadges.Append("</user>");
    }
    return UsersBadges.ToString();
}

public string AssignBadge(string BadgeId, string provider, string oauthId)
{
//" { \"award_id\": \"50001\" }";//
string result =BadgeUtils.PostCreateBadgeAward(BadgeId, provider, oauthId, "WeSpot");
return result;
}


[HttpGet]
public String getReport(string user, string timeRangeTabData, string timeValueTabData, string inquiryId)
{


//Recupero tutti gli utenti e prendo l'ultimo evento per avere la posizione
WeSpot.Models.elgg elggList = ElggUtils.GetInquiryUsers(inquiryId + "");


ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId + "");
DateTime startDate = DateTime.Now;
DateTime searchDate = DateTime.Now;

if (timeRangeTabData.Equals("Mins"))
{
    searchDate = startDate.AddMinutes(- Double.Parse(timeValueTabData));
}
if (timeRangeTabData.Equals("Hour"))
{
    searchDate = startDate.AddHours(- Double.Parse(timeValueTabData));

}
if (timeRangeTabData.Equals("Days"))
{
    searchDate = startDate.AddDays(- Double.Parse(timeValueTabData));

}
if (timeRangeTabData.Equals("Years"))
{
    searchDate = startDate.AddYears(- int.Parse(timeValueTabData));
}
StringBuilder data = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-16\"?><report xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">"
+ "<searchDate>" + searchDate + "</searchDate>"
+ "<user>"
+ "<IdUtente>" + user + "</IdUtente>"
+ "<username>" + ((Hashtable)(Session["OauthIdTOUserName"]))[user] + "</username>");


var xml = ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", searchDate, Session["oauthProvider"].ToString(), Session["oauthID"].ToString())).OuterXml;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList elemListResponseValue = doc.GetElementsByTagName("responseValue");
XmlNodeList elemListUserEmail = doc.GetElementsByTagName("userEmail");
XmlNodeList elemListTimestamp = doc.GetElementsByTagName("timestamp");
XmlNodeList elemListLat = doc.GetElementsByTagName("lat");
XmlNodeList elemListLng = doc.GetElementsByTagName("lng");
  
for (int i = 0; i < elggList.result.array_item.Length; i++)
{
    if(elggList.result.array_item[i].oauthId.Value.Equals(user))
    {
        var oauthId = elggList.result.array_item[i].oauthId.Value;
        var oauthProvider = elggList.result.array_item[i].oauthProvider.Value;
        for (int ii = 0; ii < elemListUserEmail.Count; ii++)
        {
            if (elemListUserEmail[ii].InnerXml.Contains(user))
            {

                //numImage += Regex.Matches(elemList[ii].InnerXml, "imageUrl").Count;
                //numtext += Regex.Matches(elemList[ii].InnerXml, "text").Count;
                //numaudio += Regex.Matches(elemList[ii].InnerXml, "audioUrl").Count;
                //numvideo += Regex.Matches(elemList[ii].InnerXml, "videoUrl").Count;
                //"{\"imageUrl\":\"http:\\/\\/streetlearn.appspot.com\\/uploadService\\/5333280001884160\\/2:101299949983147474204\\/image-1609631705.jpg\",\"width\":1944,\"height\":2592}"
                //"{\"audioUrl\":\"http:\\/\\/streetlearn.appspot.com\\/uploadService\\/5333280001884160\\/2:101299949983147474204\\/2689493869.m4a\"}"
                string url = "";
                string height = "";
                string width = "";
                string description = "";
                string type = "";
                JObject obj = JObject.Parse(elemListResponseValue[ii].InnerXml);


                if (obj["imageUrl"] != null)
                {
                    url = (string)obj["imageUrl"];
                    height = (string)obj["height"];
                    width = (string)obj["width"];
                    description = "Image " + height + "x" + width;
                    type = "imageUrl";
                }
                if (obj["audioUrl"] != null)
                {
                    url = (string)obj["audioUrl"];
                    description = "Audio";
                    type = "audioUrl";
                }
                if (obj["videoUrl"] != null)
                {
                    url = (string)obj["videoUrl"];
                    description = "Video";
                    type = "videoUrl";
                }

                if (obj["text"] != null)
                {
                    url = (string)obj["text"];
                    description = "Text";
                    type = "text";
                }
                if (obj["value"] != null)
                {
                    url = (string)obj["value"];
                    description = "Numeric";
                    type = "value";
                }






                //string url = elemListResponseValue[ii].InnerXml.Substring(elemListResponseValue[ii].InnerXml.IndexOf("http"), elemListResponseValue[ii].InnerXml.IndexOf(",") - elemListResponseValue[ii].InnerXml.IndexOf("http") - 1);


                var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(Double.Parse(elemListTimestamp[ii].InnerXml) / 1000d)).ToLocalTime();

                url = url.Replace(@"\", string.Empty);


                data.Append("<action>"

                  + "<actionType type=\"string\">" + type + "</actionType>"
                  + "<actionDescription type=\"string\">" + description + "</actionDescription>"
                  + "<actionDate type=\"string\">" + dt.ToString() + "</actionDate>"
                  + "<actionImage type=\"string\">" + url + "</actionImage>"
                  + "<actionLat type=\"string\">" + elemListLat[ii].InnerXml + "</actionLat>"
                  + "<actionLon type=\"string\">" + elemListLng[ii].InnerXml + "</actionrLon>"
                  + "</action>");
            }
        }
//Console.WriteLine(elemList[ii].InnerXml);
}



}
data.Append("</user>"
+ "</array_item></result></report>");
return data.ToString();
        /*
        String test = "<?xml version=\"1.0\" encoding=\"utf-16\"?><report xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">"
        + "<user>"
        + "<IdUtente>A</IdUtente>"
        + "<actions>"
        + "<action>"
        + "<actionType type=\"string\">C</actionType>"
        + "<actionDescription type=\"string\">desrizione dell azione</actionDescription>"
        + "<actionDate type=\"string\">24/02/2014</actionDate>"
        + "<actionImage type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium</actionImage>"
        + "<actionLat type=\"string\">45.066866</actionLat>"
        + "<actionLon type=\"string\">7.666740</actionrLon>"
        + "</action>"

        + "<actions/>"
        + "</user>"

        + "</array_item></result></report>";

        return test;*/
        }

        [HttpGet]
        public void printReport(string user, string timeRangeTabData, string timeValueTabData,string inquiryId)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Report_User_" + ((Hashtable)(Session["OauthIdTOUserName"]))[user].ToString().Replace(' ','_') + ".pdf");
            Response.AddHeader("Set-Cookie","fileDownload=true; path=/");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();

            StringBuilder page = new StringBuilder();

            page.Append(createHtmlDocument(user, timeRangeTabData, timeValueTabData, inquiryId));

            sw.Write(page.ToString());
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }


        private string createHtmlDocument(string user, string timeRangeTabData, string timeValueTabData,string inquiryId)
        {


            //Recupero tutti gli utenti e prendo l'ultimo evento per avere la posizione
            WeSpot.Models.elgg elggList = ElggUtils.GetInquiryUsers(inquiryId + "");


            ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId + "");
            DateTime startDate = DateTime.Now;
            DateTime searchDate = DateTime.Now;

            if (timeRangeTabData.Equals("Mins"))
            {
                searchDate = startDate.AddMinutes(-Double.Parse(timeValueTabData));
            }
            if (timeRangeTabData.Equals("Hour"))
            {
                searchDate = startDate.AddHours(-Double.Parse(timeValueTabData));

            }
            if (timeRangeTabData.Equals("Days"))
            {
                searchDate = startDate.AddDays(-Double.Parse(timeValueTabData));

            }
            if (timeRangeTabData.Equals("Years"))
            {
                searchDate = startDate.AddYears(-int.Parse(timeValueTabData));
            }
            StringBuilder page = new StringBuilder();
            page.Append("<table border='0' width='600' cellspacing='0' cellpadding='0'>");

            page.Append("<tr>");
            page.Append("<td>" + "<font face='Arial' size='4' color='#876E3A'><b> " + ((Hashtable)(Session["OauthIdTOUserName"]))[user] + " Activity Report - date filter : " + searchDate + "</b></font>" + "</td>");
            page.Append("</tr>");

            var xml = ARLearnUtils.JsonToXML(ARLearnUtils.GetRunResponses(runElgg.result.Value + "", searchDate, Session["oauthProvider"].ToString(), Session["oauthID"].ToString())).OuterXml;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList elemListResponseValue = doc.GetElementsByTagName("responseValue");
            XmlNodeList elemListUserEmail = doc.GetElementsByTagName("userEmail");
            XmlNodeList elemListTimestamp = doc.GetElementsByTagName("timestamp");
            XmlNodeList elemListLat = doc.GetElementsByTagName("lat");
            XmlNodeList elemListLng = doc.GetElementsByTagName("lng");

            for (int i = 0; i < elggList.result.array_item.Length; i++)
            {
                var oauthId = elggList.result.array_item[i].oauthId.Value;
                var oauthProvider = elggList.result.array_item[i].oauthProvider.Value;
                for (int ii = 0; ii < elemListUserEmail.Count; ii++)
                {
                    if (elemListUserEmail[ii].InnerXml.Contains(user))
                    {
                        //string url = elemListResponseValue[ii].InnerXml.Substring(elemListResponseValue[ii].InnerXml.IndexOf("http"), elemListResponseValue[ii].InnerXml.IndexOf(",") - elemListResponseValue[ii].InnerXml.IndexOf("http") - 1);
                        string url = "";
                        string height = "";
                        string width = "";
                        string description = "";
                        string type = "";
                        JObject obj = JObject.Parse(elemListResponseValue[ii].InnerXml);

                        if (obj["imageUrl"] != null)
                        {
                            url = "<img src='" +(string)obj["imageUrl"]+ "'>";
                            height = (string)obj["height"];
                            width = (string)obj["width"];
                            description = "Image " + height + "x" + width;
                            type = "imageUrl";
                        }
                        if (obj["audioUrl"] != null)
                        {
                            url = "<font face='Arial' size='2' color='#876E3A'>" + (string)obj["audioUrl"] + "</font>";
                            description = "Audio";
                            type = "audioUrl";
                        }
                        if (obj["videoUrl"] != null)
                        {
                            url = "<font face='Arial' size='2' color='#876E3A'>" + (string)obj["videoUrl"] + "</font>";
                            description = "Video";
                            type = "videoUrl";
                        }

                        if (obj["text"] != null)
                        {
                            url = (string)obj["text"];
                            description = "Text";
                            type = "text";
                        }
                        if (obj["value"] != null)
                        {
                            url = (string)obj["value"];
                            description = "Numeric";
                            type = "value";
                        }
                        
                        
                        
                        
                        var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(Double.Parse(elemListTimestamp[ii].InnerXml) / 1000d)).ToLocalTime();

                        url = url.Replace(@"\", string.Empty);

                        
                        page.Append("<tr>");
                        page.Append("<td>" + "<font face='Arial' size='3' color='#876E3A'><b>" + description + "-" + dt.ToString() + "</b></font>" + "</td>");
                        page.Append("</tr>");
                        page.Append("<tr>");

                        page.Append("<td><font face='Arial' size='2' color='#876E3A'>" + url + "</font></td>");
                        page.Append("<td>" + "" + "</td>");
                        page.Append("</tr>");

                        //"<actionLat type=\"string\">" + elemListLat[ii].InnerXml + "</actionLat>"
                        //"<actionLon type=\"string\">" + elemListLng[ii].InnerXml + "</actionrLon>"

                    }
                }
                i = elggList.result.array_item.Length;
            }
            page.Append("</table>");
            return page.ToString();
        }


        /// <summary>
        /// Get the chat list for an inquiry
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetThreadList(int inquiryId)
        {

            return getThreadList(inquiryId);//ARLearnUtils.JsonToXML(xxx).OuterXml;
        }


        private string getThreadList(int inquiryId)
        {
            var oauthID = HttpContext.Session["oauthID"];
            var oauthProvider = HttpContext.Session["oauthProvider"];

            var oauthIDSimple = extractUser(oauthID.ToString(), oauthProvider.ToString());
            var oauthProviderSimple = convertProvider(oauthProvider.ToString());


            StringBuilder data = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-16\"?><threadsList xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">"
                + "<threads>"
                + "<user>"
                + "<IdUtente>" + oauthID + "</IdUtente>"
                + "<IdUtenteProvider>" + oauthProvider + "</IdUtenteProvider>"
                + "<username>" + ((Hashtable)(Session["OauthIdTOUserName"]))[oauthID] + "</username>"
                + "</user>");

            //328 0182 434
            ElggInquiryArlearnRunModels.elgg runElgg = ElggUtils.GetInquiryArlearnRun(inquiryId + "");
            var inquiryRunId = runElgg.result.Value;
            data.Append("<runId>" + inquiryRunId + "</runId>");


            string xxx = ARLearnUtils.GetThreads(inquiryRunId + "", (string)Session["oauthProvider"], (string)Session["oauthID"]);
            JObject o = JObject.Parse(xxx);
            if (o["threads"] != null)
            {
                for (int i = 0; i < ((JArray)(o["threads"])).Count; i++)
                {
                    string runId = (string)(o["threads"][i]["runId"]);
                    string threadId = (string)(o["threads"][i]["threadId"]);
                    string name = (string)(o["threads"][i]["name"]);
                    
                     
                    string deleted = (string)(o["threads"][i]["deleted"]);
                    string lastModificationDate = (string)(o["threads"][i]["lastModificationDate"]);
                    var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(Double.Parse(lastModificationDate) / 1000d)).ToLocalTime();
                    if (name.Equals("Default"))
                    {
                        data.Append("<thread>"
                          + "<runId type=\"string\">" + runId + "</runId>"
                          + "<threadId type=\"string\">" + threadId + "</threadId>"
                          + "<name type=\"string\">" + name + "</name>"
                          + "<deleted type=\"string\">" + deleted + "</deleted>"
                          + "<lastModificationDate type=\"string\">" + dt.ToString() + "</lastModificationDate>"
                          + "</thread>");
                        i = ((JArray)(o["threads"])).Count;
                    }
                }
                //
            }
            data.Append("</threads>"
            + "</array_item></result></threadsList>");
            return data.ToString(); //ARLearnUtils.JsonToXML(xxx).OuterXml;
        }

        public string DeleteThread(string threadId, string inquiryId)
        {
            return getThreadList(int.Parse(inquiryId));
        }


        /// <summary>
        /// Get single chat thread
        /// </summary>
        /// <param name="threadId"></param>
        /// <returns></returns>
        public string GetThreadMessages(string threadId)
        {
            return this.getThreadMessages(threadId);
        }

        private string getThreadMessages(string threadId)
        {
            /*
             "<root type=\"object\">
                <type type=\"string\">org.celstec.arlearn2.beans.run.MessageList</type>
                <serverTime type=\"number\">1407426437885</serverTime>
                <messages type=\"array\">


                <item type=\"object\"><type type=\"string\">org.celstec.arlearn2.beans.run.Message</type>
                <runId type=\"number\">5333280001884160</runId>
                <deleted type=\"boolean\">false</deleted>
                <subject type=\"string\"></subject>
                <body type=\"string\">Test Message</body>
                <threadId type=\"number\">5023898475167744</threadId>
                <messageId type=\"number\">5808197084381184</messageId>
                <date type=\"number\">1407424820276</date>
                <senderId type=\"string\">101299949983147474204</senderId>
                <senderProviderId type=\"number\">2</senderProviderId></item>

                <item type=\"object\">
                <type type=\"string\">org.celstec.arlearn2.beans.run.Message</type>
                <runId type=\"number\">5333280001884160</runId>
                <deleted type=\"boolean\">false</deleted>
                <subject type=\"string\"></subject>
                <body type=\"string\">Test Message</body>
                <threadId type=\"number\">5023898475167744</threadId>
                <messageId type=\"number\">5817532195799040</messageId>
                <date type=\"number\">1407424784037</date>
                <senderId type=\"string\">101299949983147474204</senderId>
                <senderProviderId type=\"number\">2</senderProviderId>
                </item></messages>
                </root>"	string
             */
            StringBuilder data = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-16\"?><messagesList xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><status type=\"integer\">0</status><result type=\"array\"><array_item type=\"array\">"
               + "<messages>");

            JObject o = JObject.Parse(ARLearnUtils.GetThreadMessages(threadId, (string)Session["oauthProvider"], (string)Session["oauthID"]));

            JArray messages = (JArray)(o["messages"]);
            for (int i = 0; i < messages.Count; i++)
            {
                var messageMessageId = o["messages"][i]["messageId"].ToString();
                var messageRunId = o["messages"][i]["runId"].ToString();
                var messageThreadId = o["messages"][i]["threadId"].ToString();
                var messageDate = o["messages"][i]["date"].ToString();
                var messageBody = o["messages"][i]["body"].ToString();
                var messageSenderId = o["messages"][i]["senderId"].ToString();
                var messageSenderProviderId = o["messages"][i]["senderProviderId"].ToString();


                var messageUserName = ((Hashtable)(Session["OauthIdTOUserName"]))[messageSenderId];
                //var messageUserProvider = ((Hashtable)(Session["OauthIdTOProvider"]))[messageSenderId];
                var messageUserIcon = ((Hashtable)(Session["OauthPlusProviderIdTOIcon"]))[messageSenderId + "_" + ARLearnUtils.GetProviderDescription(int.Parse(messageSenderProviderId))];

                data.Append("<message>");
                data.Append("<messageMessageId>" + messageMessageId + "</messageMessageId>");
                data.Append("<messageRunId>" + messageRunId + "</messageRunId>");
                data.Append("<messageThreadId>" + messageThreadId + "</messageThreadId>");
                double timestampD;
                Double.TryParse(messageDate,out timestampD);
                var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(timestampD / 1000d)).ToLocalTime();

                data.Append("<messageDate>" + dt + "</messageDate>");
                data.Append("<messageBody>" + messageBody + "</messageBody>");
                data.Append("<messageSenderId>" + messageSenderId + "</messageSenderId>");
                data.Append("<messageSenderProviderId>" + messageSenderProviderId + "</messageSenderProviderId>");
                data.Append("<messageUserName>" + messageUserName + "</messageUserName>");
                data.Append("<messageUserIcon>" + messageUserIcon + "</messageUserIcon>");
                data.Append("</message>");
            }

            data.Append("</messages>"
            + "</array_item></result></messagesList>");
            return data.ToString();
            //ARLearnUtils.JsonToXML(ARLearnUtils.GetThreadMessages(threadId, (string)Session["oauthProvider"], (string)Session["oauthID"])).OuterXml;
        }

        public string CreateMessage(string runId, string ThreadIdString, string subjectString, string bodyString, string userId, string provider, string oauth, string inquiryId)
        {
            //string resultCreateMessage = ARLearnUtils.PostCreateMessage(runId,subjectString,bodyString,provider,oauth);
            string resultCreateMessage = ARLearnUtils.PostCreateMessage(runId, ThreadIdString,subjectString, bodyString,userId, provider, oauth);
            return this.getThreadMessages(ThreadIdString);
        }

        public string CreateThread(string runId, string treadName, string provider, string oauth, string inquiryId)
        {
            string resultCreateThread = ARLearnUtils.PostCreateThread(runId, treadName, provider, oauth);
            //TO DO una verifica ??

            return getThreadList(int.Parse(inquiryId));
        }
        /***********************************************************/

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Secure/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Secure/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Secure/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Secure/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Secure/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
